package com.zmx.base.service;

import com.nepxion.aquarius.cache.annotation.CachePut;
import com.nepxion.aquarius.cache.annotation.Cacheable;
import com.zmx.common.common.contents.cache.BaseCacheConstents;
import com.zmx.base.dto.BaseMemberCommunityRelationDto;
import com.zmx.base.entity.BaseCommunity;
import com.zmx.base.entity.BaseMemberCommunityRelation;
import com.zmx.base.repository.BaseCommunityRepository;
import com.zmx.base.repository.BaseMemberCommunityRelationRepository;
import com.zmx.base.service.mapper.BaseMemberCommunityRelationMapper;
import com.zmx.common.common.contents.cache.Expire;
import com.zmx.common.common.exception.BusinessException;
import com.zmx.common.common.invocation.InvocationInfoProxy;
import com.zmx.common.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhaomxr
 */
@Service
public class BaseMemberCommunityRelationService extends BaseService<BaseMemberCommunityRelation, BaseMemberCommunityRelationDto, BaseMemberCommunityRelationRepository, BaseMemberCommunityRelationMapper> {

    @Autowired
    private BaseCommunityRepository baseCommunityRepository;

    /**
     * 查询用户选择的区域
     * @return
     */
    @Cacheable(name = BaseCacheConstents.MEMBER_COMMUNITY, key = "'getCommunity'", expire = Expire.FOREVER)
    public BaseMemberCommunityRelationDto getCommunity() {
        BaseMemberCommunityRelationDto memberCommunityRelationDTO = new BaseMemberCommunityRelationDto();
        Long memberId = Long.valueOf(InvocationInfoProxy.getUserId());
        BaseMemberCommunityRelation memberCommunityRelation = repository.getByMemberId(memberId);

        if (memberCommunityRelation != null) {
            BaseCommunity community = baseCommunityRepository.findById(memberCommunityRelation.getCommunityId());
            memberCommunityRelationDTO.setCommunityName(community.getName());
        }

        return memberCommunityRelationDTO;
    }

    /**
     * 新增区域选择记录
     * @param communityId
     */
    @CachePut(name = BaseCacheConstents.MEMBER_COMMUNITY, key = "'getCommunity'", expire = Expire.FOREVER)
    public void addMemberCommunity(Long communityId) {
        if (communityId == null || communityId <= 0) {
            throw new BusinessException("");
        }

        Long memberId = Long.valueOf(InvocationInfoProxy.getUserId());
        BaseMemberCommunityRelationDto memberCommunityRelationDto = new BaseMemberCommunityRelationDto();
        memberCommunityRelationDto.setMemberId(memberId);
        memberCommunityRelationDto.setCommunityId(communityId);
        memberCommunityRelationDto.setIsValid(1);
        this.create(memberCommunityRelationDto);
    }
}
